<script setup>
/**
 * @name 图文剪辑发布抽屉
 */

import { useForm } from 'ant-design-vue/lib/form';
import {
    reactive, ref, watch, computed, inject, 
    defineAsyncComponent,
    nextTick,
    unref,
 } from 'vue';
import {QuestionCircleOutlined, CloseOutlined,PlusOutlined} from "@ant-design/icons-vue";

// 图集成片
import ClipHightGroupList from "../../MatrixMarketing/modules/ClipHightGroupList.vue"

// 选择账号弹窗
import ChooseAccountModal from "@/views/shotstack/MatrixMarketing/modules/ChooseAccountModal.vue";
const chooseAccountModalRef = ref()
import request from "@/common/utils/request";
import _ from 'lodash';
import dayjs from 'dayjs';
import { message,Empty } from 'ant-design-vue';
import { useRouter } from 'vue-router';

const simpleImage=ref(Empty.PRESENTED_IMAGE_SIMPLE)

const emit = defineEmits(["submit"]);

const router = useRouter()
// 时区相关
const { getTimezoneList , currentTimezone} = inject('timezone');
let timezones = getTimezoneList();

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  isPicTxtTask:{
    type:Boolean,
    default:false
  },
  data: {
    type: Object,
    default: () => ({}),
  },
  taskId: {
    type: [Number, String],
    default: 0,
  },
  source:{//平台
    type:String,
    default:''
  },
  isLongArticle:{//是否是长文创作包括任务和文章
    type:Boolean,
    default:false
  },
  isAll:{//是否是自动发布
    type:Boolean,
    default:false
  },
  // 使用的地方
  useType: {
    type: String,
    default:'图片成片'
  },
});

const douyinForm = defineAsyncComponent(() => import("@/views/shotstack/MaterialCenter/modules/modules/DouyinForm.vue"));
const kuaishouForm = defineAsyncComponent(() => import("@/views/shotstack/MaterialCenter/modules/modules/KuaishouForm.vue"));
const xiaohongshu = defineAsyncComponent(() => import("@/views/shotstack/MaterialCenter/modules/modules/RedBookForm.vue"));

let formComponents = {
  douyin: douyinForm,
  xiaohongshu: xiaohongshu,
  kuaishou:kuaishouForm
}

const currentComponentKey = computed(() => {
  return formComponents[formData.source];
});

// 选择的文章列表
const cascader_task_id = ref([])

// 动态组件实例
const componentRef = ref()

const state = reactive({
    // 抽屉开关
  visible: false,
    // 提交按钮 loading
    btnLoading:false,
    // 选择任务 options
    options:[
    {
        label: '图文创作',
        value:2,
        isLeaf: false,
        children:[]
    },
    {
        label: '文章创作',
        value:1,
        isLeaf: false,
        children:[]
        }
    ],
    // 选择的账户
    accountList:[],

    groupList: [],

   clipHightGroupVisible: false
})

const workTypeList = [
  { label: "仅工作时间段执行", value: 1 },
  { label: "全天均可执行", value: 0 },
];

let dayList = [
  { label: "1天(立即)", value: 1 },
  { label: "2天", value: 2 },
  { label: "3天", value: 3 },
  { label: "4天", value: 4 },
  { label: "5天", value: 5 },
  { label: "6天", value: 6 },
  { label: "7天", value: 7 },
];
let hourList = [
  { label: "立即发布", value: 0 },
  { label: "1小时", value: 1 },
  { label: "2小时", value: 2 },
  { label: "3小时", value: 3 },
  { label: "4小时", value: 4 },
  { label: "5小时", value: 5 },
  { label: "6小时", value: 6 },
  { label: "7小时", value: 7 },
  { label: "8小时", value: 8 },
  { label: "9小时", value: 9 },
  { label: "10小时", value: 10 },
];

// 动态组件数据
let componentData = ref({
  // 定时发布时间
  fix_at: "",
  // 发布时间模式: 1立即, 2定时
  publish_type: "1",
  // 封面数据(后端自己取)
  cover_img: [],
  // 话题列表
  challenges: [],
  // 是否允许他人保存图片
  download: "1",
  // 谁可以看
  visibility_type: "0",
  // 选择的音乐
  music_id: "",
  // 选择的音乐结束时间
  music_end_time: "",
  // 小红书话题??
  hash_tag: [],
  // 小红书 公开或仅自己可见
  is_private: 0,
  // 图文描述
  des:[],
  // 貌似无用
  publishType: 1,
  poster: [],
  poi_id_info:[],

});

// 平台列表
const platformOptions = ref([])

// 头部进度条数据
const stepsData = reactive({
    steps: [{ title: '任务设置' }, { title: '发布设置' }],
    current:0
})

const rulesRef = reactive({
    accountList: [{ required: true, message: "发布账号不能为空" }],
    source: [{ required: true, message: "请选择平台" }],
});

// 提交的数据
let formData = reactive({
    // 备注
    remarks: "",
    // 账号列表
    accountList: [],
    publishDay: 1,
    publishDuring: 0,
    type: 0,
    workType: 0,
    // 选择的平台
    source: null,
    utc_offset: currentTimezone.value,
    // 图文剪辑 任务id
    business_id:[]
});

const { resetFields, validate, validateInfos } = useForm(formData, rulesRef);

const currentAccountId = computed(() => {
  return formData.accountList.length ? formData.accountList[0].id : "";
});

let timezoneLabel = computed(() => {
  return timezones.find((item) => item.value == formData.utc_offset)
    ?.label??''
});

// 写个函数如果传入的值小于1 单位是小时  如果小于1 转换成分钟
const getTime = (value) => {
  if (value < 1) {
    return Math.ceil(value * 60) + "分钟";
  }
  return Math.ceil(value) + "小时";
};

// 选择账号 禁用逻辑 -- 没有选择平台 则禁用
const disabledBtn = computed(() => {
    return !formData.source
})

// 当前平台下的账号数量
const accountCount = computed(() => {
 let count = platformOptions.value.find(item=>item.key==formData.source)?.subCount??1
 return count?count:1
});

// 选中的图文数量
const selectedCount = computed(() => {
  return formData.business_id?.length
});

//发布图文用的天数
const publishDays = computed(() => {
  return formData.publishDay;
});

// 每天发布数量
const publishCountPerDay = computed(() => {
  const count = selectedCount.value / publishDays.value / accountCount.value
  return count
});

//实际发布天数
const realDays = computed(() => {
  // debugger
  return publishCountPerDay.value>=1?publishDays.value:Math.ceil(selectedCount.value/accountCount.value)
});

// 每天每个账号发布
const publishArticleCountPerDay = computed(() => {
  let count = Math.ceil(publishCountPerDay.value);

  if(count == 1){
    return 1
  }

  let subCount = Math.floor(publishCountPerDay.value);

  if(count == subCount){
    return count
  }

  return `${subCount} ~ ${count}`
});

// 每天发布用的小时数
const hourCountPerDay = computed(() => {
  return formData.publishDuring;
});

//每天多少时间发布一遍文章
const publishHour = computed(() => {
  return getTime(hourCountPerDay.value / Math.ceil(publishCountPerDay.value));
});

// 选择账号
const showAccount = () => {
    console.log(formData.source, '选的平台--------source');
    if(state.groupList.length){
      formData.business_id = state.groupList.map((item)=>item.image_text_record_detail_id)
    }
    chooseAccountModalRef.value?.showModal(formData.accountList)
}

    // 选择账号弹窗 回调
const onSuccessChooseAccount = (info) => {
    if (info.length) {
        formData.accountList = _.uniqBy(info, "id");
    }
    formData.accountList = formData.accountList.map(account => ({
        ...account, // 拷贝原有属性
        enablePostWithProduct: false,
        reachLimit: false,
        weixinshipinhao_loading: false,
        is_success: false
    }));
    chooseAccountModalRef.value?.closeModal()
}

// 删除某个选择的账号
const closeAccount = (index) => {
  formData.accountList.splice(index, 1);
};

// 获取平台接口
let platformtList = ref([])
const getPlatformList = () => {
  request.get("/work_ai", "/org/platform/account/shotStackList", { imageTextRelease: 1}).then((res) => {
    platformtList.value = res?.result
  });
};

//处理抖音平台多选音乐,随机把音乐分配个多个账户
const handleMultiple = (accouts,musics)=>{
  console.log(musics);
    if(accouts.length<=musics.length){
      accouts.map((item,index)=>{
        item.data.music_id = musics[index].id,
        item.data.music_end_time = musics[index].duration*1000
      })
    }else{
      accouts.map((item,index)=>{
        item.data.music_id = musics[index%musics.length].id,
        item.data.music_end_time = musics[index%musics.length].duration*1000
      })
    }
    return accouts
}


const generateTaskString = () => {
    let timezoneOffset = currentTimezone.value
    // 获取当前时间并应用时区偏移
    const date = dayjs().utcOffset(timezoneOffset * 60);

    const month = date.format('MM');
    const day = date.format('DD');
    const hours = date.format('HH');
    const minutes = date.format('mm');
    const seconds = date.format('ss');

    return `任务${month}${day}-${hours}${minutes}-${seconds}`;
}

// 确定提交
const ok = async () => {
  validate().then(async () => {
    state.btnLoading = true
    if (componentRef.value) {
      console.log(componentRef.value,'是啥componentRef.value');
      
      const res = await componentRef.value?.validateData && componentRef.value?.validateData();
    }
    let info = unref(componentData.value)
    // if(!info.poi_id_info || Object.keys(info.poi_id_info).length==0){
    if(Array.isArray(info.poi_id_info) && !info.poi_id_info.length){
        delete info.poi_id_info
    }
    let accouts = formData.accountList.map((item) => {
      return {
        account_id: item.id,
        data:info,
      };
    });
    // 处理抖音平台多选音乐，多选并且是抖音平台
    if(componentRef?.value?.musics?.length>0){
      accouts = handleMultiple(accouts,componentRef.value.musics)
    }
    let params = {
      account: accouts,
      is_deduplication: formData.is_filter ? 1 : 0,
      article_image_type: formData.type,
      remark: formData.remarks,
      business_type: props.useType == '图片成片' ? "image_text_record" : "image_text_record_atlas",
      // 发布的 图文剪辑任务id
      business_id:formData.business_id,
      // 发布的平台
      platform:formData.source,
      utc_offset: accouts[0]?.data?.utc_offset,
      publish_day: formData.publishDay,
      publish_hour: formData.publishDuring,
      work_type: formData.workType,
    };
    console.log(accouts, 'accoutsaccouts');

    if(!params.remark){//默认添加一个备注
      params.remark = generateTaskString()
    }

    console.log(params, '提交的参数????');

    // return
    
    request
      .post("/work_ai", "/user/image/clip/publish/add", params)
      .then((res) => {
        console.log(res);
        if (res?.code && res?.code != 1000) {
          message.error(res?.msg || '发布失败!')
          return
        }
        emit('submit')
        message.success('发布任务提交成功!')
        close()
        router.push({
          name: 'ReleaseList',
          query:{
            viewActiveKey:'图文'
          }
        })
      })
      .catch(() => {  state.btnLoading = false});

    // emit("submit");
  }).catch(err => {
    console.log(err, '什么错');
    const msg = err?.errorFields?.[0]?.errors?.[0]
    message.error(msg || '请完善发布信息')
    // stepsData.current = 1
    // state.btnLoading = false
  }).finally(() => {
    stepsData.current = 1
    state.btnLoading = false
  })
};

const open = (params={}) => {
  const { business_id = [],accountKey=''} = params
  // 存放发布图文剪辑的 任务id
  console.log(business_id,'发布图文剪辑任务id');
    state.groupList = business_id 
    formData.source = accountKey
    formData.business_id = business_id.map(ele => ele.image_text_record_detail_id)
    getPlatformList()


    state.visible = true
}

const close = () => {
  state.visible = false
  state.groupList = []
}

defineExpose({
    open,
    close
})


const closeImgClick= (index)=>{
  state.groupList = state.groupList.filter((item,i)=>i != index)
  formData.accountList.splice(index,1)
}

const addImg=()=>{
  state.clipHightGroupVisible = true
}

const submitChange=({checkList,accountKey})=>{
  state.groupList = checkList
  if(!formData.source){
    formData.source = accountKey
  }
  state.clipHightGroupVisible = false
}

const closeChange=()=>{
  state.clipHightGroupVisible = false
  console.log('11132321321');
}

</script>

<template>
    <div class="ImageTextIssue">
    <a-drawer
    width="700px"
    :maskClosable="false"
    title="新建发布任务"
    :destroyOnClose="true"
    :visible="state.visible"
    @close="close"
    :bodyStyle="{ paddingRight: 0 }"
  >
    <div class="step-wrapper">
        <a-steps v-model:current="stepsData.current">
      <a-step v-for="item in stepsData.steps"  :key="item.title" :title="item.title" />
    </a-steps>
    </div>
    <div class="content-wrapper beauty-scroller-bar">
      <a-form class="mt-20" layout="vertical">
        <a-form-item v-if="stepsData.current==0">
          <template #label >
            <a-row style="width: 655px;" justify="space-between" align="middle">
              <a-col>
                图集成片
              </a-col>
              <a-col >
                <a-button type="link" @click.stop="addImg"> <plus-outlined /> 添加图集</a-button>
              </a-col>
            </a-row>
          </template>
          <a-row :gutter="[16,16]" v-if="state.groupList?.length > 0" class="beauty-scroller-bar" style="padding:10px 5px; max-height:300px; overflow-y: auto;" >
            <a-col :span="6" v-for="(item, index) in state.groupList"
                  :key="item.id">
                  <div class="group-box">
                    <img
                    v-lazy="item?.medias?.[0]?.material_url"
                    class="group-image"
                    style=""
                    />
                    <div class="close-mask" @click.stop="closeImgClick(index)"> 
                      <close-outlined />
                    </div>
                  </div>
            </a-col>
          </a-row>
          <div v-else>
                <a-empty :image="simpleImage" />
          </div> 
       </a-form-item>

        <!-- 选择平台-->
        <a-form-item
          v-bind="validateInfos.source"
          v-if="stepsData.current==0"
        >
        <template #label>
          平台
        </template>
          <a-select
            v-model:value="formData.source"
            option-label-prop="children"
            placeholder="请选择平台"
            @change="formData.accountList = []"
          >
            <a-select-option v-for="item in platformtList" :value="item?.key">
              <a-image
                :preview="false"
                :width="20"
                :height="20"
                :src="item?.image"
              />
              &nbsp;{{ item?.value }}（{{ item.subCount }}个账号）
            </a-select-option>
          </a-select>
        </a-form-item>

        <!-- 
                选择发布账号
        -->
        <a-form-item v-if="stepsData.current==0" v-bind="validateInfos.accountList">
          <template #label>
            <span class="mr-5">选择发布账号</span>
            <a-tooltip>
            <template #title>
              需要先选择平台
            </template>
            <QuestionCircleOutlined/>
             </a-tooltip>
          </template>

          <div>
            <a-button
              :disabled="disabledBtn"
              type="primary"
              @click="showAccount"
              >选择账号</a-button
            >
          </div>
          <div class="account-list">
            <a-tag
              style="margin-bottom: 5px"
              closable
              @close="closeAccount(index)"
              v-for="(account, index) in formData.accountList"
              :key="account.id"
            >
              <img class="img-icon" :src="account?.avatar" />
              <!-- <img class="img-icon" :src="getImgIcon(account.source)" /> -->
              {{ account.nickname }}
            </a-tag>
          </div>
          <div v-if="isShowTip" class="text-gray-5">选择多账号发布，内容将随机分布在不同的账号上</div>
        </a-form-item>

        <!-- 
                备注
        -->
        <a-form-item label="备注" v-if="stepsData.current==0" v-bind="validateInfos.remarks">
          <a-textarea
            v-model:value="formData.remarks"
            placeholder="用于区分不同任务"
            style="width: 100%"
          />
        </a-form-item>

        <!-- 
        动态组件
        -->
        <div 
        v-show="stepsData.current==1"
        >
        <!-- v-if="!disabledBtn" -->
        <component
          ref="componentRef"
          v-model:form-data="componentData"
           :accountId="currentAccountId"
          :is="currentComponentKey"
          :isShowPublishTime="true"
          :multiple="false"
          ></component>
         </div>

        <div v-show="stepsData.current==0">
            <div class="flex">
                <a-form-item
                    v-bind="validateInfos.publishDay"
                    style="flex: 1"
                    label="在几天内发布完(最长7天)"
                >
                    <a-select
                    v-model:value="formData.publishDay"
                    :options="dayList"
                    ></a-select>
                </a-form-item>
                <a-form-item
                    label="每天发布几小时"
                    v-bind="validateInfos.publishDuring"
                    style="flex: 1; margin-left: 10px"
                >
                    <a-select
                    v-model:value="formData.publishDuring"
                    :options="hourList"
                    ></a-select>
                </a-form-item>
                <!-- <a-form-item
                    label="时区"
                    v-bind="validateInfos.publishDuring"
                    style="flex: 1; margin-left: 10px"
                >
                <a-select
                    v-model:value="formData.utc_offset"
                    :options="timezones"
                ></a-select>
            </a-form-item> -->
            </div>

            <div class="mb-10">
            预计将<span
                class="main-color"
                >{{ realDays }}</span
            >天内发布完成，每天每个账号发布<span class="main-color">{{
                publishArticleCountPerDay
            }}</span
            >篇，每天发布用时<span class="main-color">{{ hourCountPerDay }}</span
            >小时，间隔每<span class="main-color">{{ publishHour }}</span
            >发布一篇
            </div>

            <a-form-item
                label="执行发布时间"
                v-bind="validateInfos.workType">
            <a-radio-group
                :options="workTypeList"
                v-model:value="formData.workType"
            >
            </a-radio-group>
            <div class="text-gray-5">
                如工作时间段执行的话，仅在 8:00-20:00（{{timezoneLabel}}） 间段内执行发布操作
            </div>
            </a-form-item>
        </div>


      </a-form>
      <div class="toutiao-tip" v-if="stepsData.current==1&&formData.source=='toutiao'||stepsData.current==1&&formData.source=='toutiao'&&selectedCount>1">头条平台无需配置，可直接发布</div>
      <div class="toutiao-tip" v-if="stepsData.current==1&&formData.source=='weixinshipinhao'||stepsData.current==1&&formData.source=='weixinshipinhao'&&selectedCount>1">微信视频号平台无需配置，可直接发布</div>

    </div>
    <div class="bottom-area">
        <a-button class="mr-20" v-if="stepsData.current==1" @click="stepsData.current = 0">上一步</a-button>
        <a-button class="mr-20" @click="stepsData.current = 1" v-else> 下一步</a-button>
      <a-button type="primary" @click="ok" v-if="stepsData.current==1" :loading="state.btnLoading">确认</a-button>
    </div>

  </a-drawer>
    </div>

    <!-- 选择账号 -->
    <ChooseAccountModal :filmVideoListLength="formData.business_id.length" 
    :sourceType="formData.source"
    @onSuccess="onSuccessChooseAccount" :useType="props.useType"
    ref="chooseAccountModalRef" />

    <!-- 图片成集 -->
    <ClipHightGroupList :visible="state.clipHightGroupVisible" :list="state.groupList" @submit="submitChange" @close="closeChange"/>
</template>



<style lang="scss" scoped>
.keywords-wrapper {
  min-height: 100px;
  border: 1px solid #ccc;
  padding: 10px;
}
.addkey {
  cursor: pointer;
}
.account-list {
  margin-top: 10px;
  :deep(.ss-tag) {
    padding: 5px;
  }
}
.main-color {
  color: #ff6f3b;
}
.content-wrapper {
  height: calc(100% - 60px);
  overflow: auto;
  padding-right: 20px;
}
.img-icon {
  width: 20px;
  height: 20px;
  margin-right: 6px;
}
.bottom-area {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  position: absolute;
  bottom: 0px;
  left: 0;
  border-top: 1px solid #eee;
 height: 60px;
 padding: 0 20px;
 background-color: #fff;
 z-index: 9;

}
.step-wrapper{
    width:100%;
    margin-bottom: 20px;
    padding-right: 20px;
}

:deep(.ss-cascader-menu-item){
      .ss-cascader-menu-item-content{
      max-width: 500px!important;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      }
}
.toutiao-tip{
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}
.group-box{
  width: 100%;
  height: 120px;
  background: #000;
  position: relative;
  border-radius: 8px;
  .group-image{
    width: 100%;
    height:120px;
    border-radius: 8px;
    object-fit: contain;
  }
  .close-mask{
    position: absolute;
    top: -8px;
    right: -8px;
    width: 20px;
    height: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 50%;
    cursor: pointer;
    color: #fff;
    background: rgba($color: #000000, $alpha: 0.5);
  }
}

</style>